package com.westar.core.job;

import com.westar.base.cons.Constant;
import com.westar.base.exceptions.SelfHttpException;
import com.westar.base.model.AffairInfo;
import com.westar.base.model.UserInfo;
import com.westar.base.pojo.WestarResult;
import com.westar.base.util.DateTimeUtil;
import com.westar.base.util.TokenUtil;
import com.westar.base.util.WestarHttpUtil;
import com.westar.core.conf.SysConst;
import com.westar.core.services.*;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobDataMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class SchedulerWestar {

    @Resource
    DynamicJobFactory dynamicJobFactory;

    @Autowired
    private AffairInfoService affairInfoService;

    @Autowired
    private AffairEditService affairEditService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private SystemLogService systemLogService;

    @Resource
    private AccountLimitService accountLimitService;

    //每隔10分钟执行一次
    @Scheduled(initialDelay = 5000,fixedRate = 1000L * 60 * 5)
    public void autoHandleAffair() {
        //当前时间
        this.noAccept();
        //受理数据
        this.toHandleFirst();
        //办理审批信息
        this.toHandleTask();
    }

    /**
     * 处理账号登录问题
     */
    @Scheduled(initialDelay = 5000,fixedRate = 1000L * 60 * 10)
    private void removeAccountLimit() {
        //处理账号登录问题
        accountLimitService.removeAccountLimit();
    }

    //1号和15号，在凌晨4点执行一次
    @Scheduled(cron = "0 0 4 1,15 * ?")
    public void autoSyncUser() {
        //查询密码的次数，判定管是否需要限定时间再次登录
        int errorCount = accountLimitService.countAccountLimit(SysConst.ADMIN_ACCOUNT);
        if(errorCount > 5 ){
            systemLogService.addSystemLog(SysConst.ADMIN_ACCOUNT,"-","-1","密码错误超过五次！");
            return;
        }
        try {
            UserInfo adminUser = userInfoService.getUserInfoByAccount(SysConst.ADMIN_ACCOUNT);
            String token = TokenUtil.initToken(adminUser.getAccount(),adminUser.getPasswd(),Constant.MODEL_OAUTHUI);
            String actCookie = TokenUtil.getCookie(token,Constant.MODEL_OAUTHUI);
            userInfoService.initUser(actCookie);
            //登录成功，删除所有的密码错误记录
            accountLimitService.deleteAccountLimit(SysConst.ADMIN_ACCOUNT);

        } catch (IOException e) {
        } catch (SelfHttpException e) {
            if(e.getCode().equals(SelfHttpException.PAGE_RE_LOGIN  ) ){
                accountLimitService.addAccountLimit(SysConst.ADMIN_ACCOUNT,errorCount);
                autoSyncUser();
            }
        }
    }
    //1号和15号，在凌晨4点执行一次
    @Scheduled(cron = "0 0 12,17 * * ?")
    public void autoSyncUsedUser() {
        //查询密码的次数，判定管是否需要限定时间再次登录
        int errorCount = accountLimitService.countAccountLimit(SysConst.ADMIN_ACCOUNT);
        if(errorCount > 5 ){
            systemLogService.addSystemLog(SysConst.ADMIN_ACCOUNT,"-","-1","密码错误超过五次！");
            return;
        }
        try {
            UserInfo adminUser = userInfoService.getUserInfoByAccount(SysConst.ADMIN_ACCOUNT);
            String token = TokenUtil.initToken(adminUser.getAccount(),adminUser.getPasswd(), Constant.MODEL_OAUTHUI);
            String actCookie = TokenUtil.getCookie(token, Constant.MODEL_OAUTHUI);
            userInfoService.initUsedUser(actCookie);

            //登录成功，删除所有的密码错误记录
            accountLimitService.deleteAccountLimit(SysConst.ADMIN_ACCOUNT);

        } catch (IOException e) {
        } catch (SelfHttpException e) {
            if(e.getCode().equals(SelfHttpException.PAGE_RE_LOGIN  ) ){
                accountLimitService.addAccountLimit(SysConst.ADMIN_ACCOUNT,errorCount);
                autoSyncUsedUser();
            }
        }
    }

//    //1号和15号，在凌晨4点执行一次
//    @Scheduled(cron = "0 0 7 1,11,21 * ?")
//    public void autoChangePwd() {
//        userInfoService.autoChangePwd();
//    }

    /**
     * 不予受理的数据
     */
    private void noAccept() {
        List<AffairInfo> affairInfoList = affairInfoService.listAffairInfoForReject();
        if(null != affairInfoList && !affairInfoList.isEmpty()) {
            for (AffairInfo affairInfo : affairInfoList) {

                String affairId = affairInfo.getAffairId();
                String account = affairInfo.getOperator();

                //查询密码的次数，判定管是否需要限定时间再次登录
                int errorCount = accountLimitService.countAccountLimit(account);
                if(errorCount > 5 ){
                    systemLogService.addSystemLog(account,"-","-1","密码错误超过五次！");
                    continue;
                }

                String token = this.getToken( account );
                if(null != token){
                    try {
                        String actCookie = TokenUtil.getCookie(token,Constant.MODEL_DOTHINGSUI);
                        WestarResult westarResult = affairEditService.noaccept(actCookie,affairId,account);
                        if(westarResult.getStatus() == 0){
                            affairInfoService.delAffairInfo(affairId);
                        }
                        //登录成功，删除所有的密码错误记录
                        accountLimitService.deleteAccountLimit(account);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (SelfHttpException e) {
                        if(e.getCode().equals(SelfHttpException.PAGE_RE_LOGIN  ) ){
                            accountLimitService.addAccountLimit(account,errorCount);
                        }

                    }

                }
            }
        }
    }

    /**
     * 将保存的办件受理
     */
    private void toHandleFirst() {
        //分页查询需要代办的信息
        List<AffairInfo> affairInfoList = affairInfoService.listAffairInfoForAutoEdit("0",new String[]{"2"});
        if(null != affairInfoList && !affairInfoList.isEmpty()){
            for (AffairInfo affairInfo:affairInfoList){
                JobDataMap jobDataMap = new JobDataMap();
                jobDataMap.put("affairInfo",affairInfo  );
                jobDataMap.put("type","editTask");

                String affairId = affairInfo.getAffairId();

                String autoHandleTime = affairInfo.getAutoHandleTime();
                String nowDateTime = DateTimeUtil.getNowDateStr( DateTimeUtil.yyyy_MM_dd_HH_mm );
                nowDateTime = DateTimeUtil.addDate(nowDateTime,DateTimeUtil.yyyy_MM_dd_HH_mm, Calendar.MINUTE,1 );

                Date one = DateTimeUtil.parseDate(autoHandleTime,DateTimeUtil.yyyy_MM_dd_HH_mm  );
                Date two = DateTimeUtil.parseDate(nowDateTime,DateTimeUtil.yyyy_MM_dd_HH_mm  );
                if(one.before(two)){
                    autoHandleTime = nowDateTime;
                }
                try {
                    String cron = DateTimeUtil.transCorn(autoHandleTime);
                    dynamicJobFactory.addJob( AffairEditScheduledService.class,jobDataMap,affairId,cron);
                } catch (ParseException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 自动办理审批信息
     */
    private void toHandleTask(){
        //分页查询需要代办的信息
        List<AffairInfo> affairInfoList = affairInfoService.listAffairInfoForAutoEdit("1",new String[]{"2"});
        if(null != affairInfoList && !affairInfoList.isEmpty()){
            for (AffairInfo affairInfo:affairInfoList){

                JobDataMap jobDataMap = new JobDataMap();
                jobDataMap.put("affairInfo",affairInfo  );
                jobDataMap.put("type","handleTask"  );

                String affairId = affairInfo.getAffairId();

                String autoHandleTime = affairInfo.getAutoHandleTime();
                String nowDateTime = DateTimeUtil.getNowDateStr( DateTimeUtil.yyyy_MM_dd_HH_mm );
                nowDateTime = DateTimeUtil.addDate(nowDateTime,DateTimeUtil.yyyy_MM_dd_HH_mm, Calendar.MINUTE,1 );

                Long one = DateTimeUtil.parseDate(autoHandleTime,DateTimeUtil.yyyy_MM_dd_HH_mm  ).getTime();
                Long two = DateTimeUtil.parseDate(nowDateTime,DateTimeUtil.yyyy_MM_dd_HH_mm  ).getTime();
                if(one <= two){
                    autoHandleTime = nowDateTime;
                }

                try {
                    String cron = DateTimeUtil.transCorn(autoHandleTime);
                    dynamicJobFactory.addJob(AffairEditScheduledService.class,jobDataMap,affairId,cron);
                } catch (ParseException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    /**
     * 获取不予受理的的账号的token
     * @param account
     * @return
     */
    private String getToken(String account) {
        String token = null;
        try {
            token = TokenUtil.getTokenByAccount(account);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SelfHttpException e) {
            e.printStackTrace();
        }

        if(null == token){
            //检查子账号信息
            userInfoService.checkExecutor(account);
            
            UserInfo userInfo = userInfoService.getUserInfoByAccount(account);
            //检查密码
            String passwd = userInfo.getPasswd();
            if(StringUtils.isEmpty(passwd) || passwd.equals("-")){
                systemLogService.addSystemLog(account,"-","-1","密码已经变动，请及时修改!");
                return null;
            }
            try {
                token = TokenUtil.initToken(account,passwd,Constant.MODEL_DOTHINGSUI);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SelfHttpException e) {
                e.printStackTrace();
            }
            //保存用户
            if(StringUtils.isNotEmpty(token)){
                UserInfo sessionuser = userInfoService.getUserInfoByAccount(account);
                sessionuser.setPasswd(userInfo.getPasswd());
                TokenUtil.updateSessionUser(token,sessionuser);
            }

        }
        return token;
    }

}
